package server

import (
	"errors"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"go_self/model"
	"go_self/util"
	"time"
)

// CategoryByList 种类列表
func CategoryByList(input map[string]string) []map[string]interface{} {
	categorySql, args := sql_aid.PgTable(model.TableByCategory).Field("id", "title", "parent_id", "parent_path", "grade").WhereIn("grade", []interface{}{model.CategoryByOne, model.CategoryByTwo}...).Where("time_d is null", nil).OrderBy("grade desc").PageSize(input["page"], input["page_size"]).ToSql()
	category, err := sql_aid.DataToMap(model.PgSql.Query(categorySql, args...))
	if err != nil || len(category) == 0 {
		return nil
	}
	categoryOne := make([]map[string]interface{}, 0)
	categoryTwo := make([]map[string]interface{}, 0)
	for _, val := range category {
		if val["grade"].(int64) == 1 {
			categoryOne = append(categoryOne, val)
		}
		if val["grade"].(int64) == 2 {
			categoryTwo = append(categoryTwo, val)
		}
	}
	categoryTwoInt64Col := util.ArrayColumnGroupByInt64(&categoryTwo, "parent_id")
	for _, valOne := range categoryOne {
		if categoryTwoInt64Col[valOne["id"].(int64)] != nil {
			valOne["children"] = categoryTwoInt64Col[valOne["id"].(int64)]
		}
	}
	return categoryOne
}

// CategoryByAdd 种类添加
func CategoryByAdd(data map[string]interface{}) error {
	attributeKeySql, args := sql_aid.PgTable(model.TableByCategory).InsertByMap(&data)
	_, err := model.PgSql.Exec(attributeKeySql, args...)
	if err != nil {
		gogo_log.Write("server_CategoryByAdd", "种类添加", err.Error())
		return errors.New("添加失败")
	}
	return nil
}

// CategoryByEdit 种类编辑
func CategoryByEdit(id string, title string) error {
	timestamp := time.Now().Format(time.RFC3339)
	update := make(map[string]interface{})
	update["title"] = title
	update["time_u"] = timestamp
	attributeKeySql, args := sql_aid.PgTable(model.TableByCategory).WhereId(id).UpdateByMap(&update)
	_, err := model.PgSql.Exec(attributeKeySql, args...)
	if err != nil {
		gogo_log.Write("server_CategoryByEdit", "种类编辑", err.Error())
		return errors.New("编辑失败")
	}
	return nil
}

// CategoryByDel 种类删除
func CategoryByDel(id int) error {
	timestamp := time.Now().Format(time.RFC3339)
	update := make(map[string]interface{})
	update["time_d"] = timestamp
	attributeKeySql, args := sql_aid.PgTable(model.TableByCategory).WhereId(id).UpdateByMap(&update)
	_, err := model.PgSql.Exec(attributeKeySql, args...)
	if err != nil {
		gogo_log.Write("server_CategoryByDel", "种类删除", err.Error())
		return errors.New("删除失败")
	}
	return nil
}
